/**
 * Created by xiaomin on 2015/6/30.
 */

var PrivilegeService = angular.module('PrivilegeService', ['ngResource']);

PrivilegeService.factory('PrivilegeService', ['$resource', '$q',
    function ($resource, $q) {

        var service = {
            getList: function (url) {
                var deferred = $q.defer();
                $resource(url, {}).get().$promise.then(
                    function (res) {
                        if (res.code == 0) {
                            var privileges = []
                            var recursion = function (p, parent) {
                                for (var i = 0; i < p.length; i++) {
                                    var item = p[i]
                                    item.pid = parent ? parent.ttId : null
                                    item.ttId = ((parent ? parent.ttId + '-' : '') + (i + 1))
                                    privileges.push(item)
                                    if (item.children)
                                        recursion(item.children, item)
                                }
                            }
                            recursion(res.privileges, null)
                            deferred.resolve(privileges);
                        } else {
                            deferred.resolve(res);
                        }

                    },
                    function (err) {
                        deferred.reject(err);
                    }
                );

                return deferred.promise;
            }
        }

        return service;
    }]);